package com.example.mywmb

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MonitoringActivity : AppCompatActivity() {
    
    private lateinit var btnEndImmediately: Button
    private lateinit var relayController: RelayController
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_monitoring)
        
        initViews()
        setupListeners()
        
        // 初始化继电器控制器
        relayController = RelayController()
        
        // 这里不需要再开启所有继电器，因为MainActivity已经设置了正确的继电器状态
        // 保持当前继电器状态即可
//        Toast.makeText(this, "设备已开启", Toast.LENGTH_SHORT).show()
    }
    
    private fun initViews() {
        btnEndImmediately = findViewById(R.id.btnEndImmediately)
    }
    
    private fun setupListeners() {
        btnEndImmediately.setOnClickListener {
            endMonitoring()
        }
    }
    
    private fun endMonitoring() {
        try {
//            Toast.makeText(this, "正在关闭设备...", Toast.LENGTH_SHORT).show()
            
            // 关闭继电器2、3、4，打开继电器1
            relayController.controlMultipleRelays(listOf(2, 3, 4), false)
            relayController.controlRelay(1, true)
            Log.d("MonitoringActivity", "立即结束：继电器2、3、4关闭，继电器1开启")
            
//            Toast.makeText(this, "设备已关闭", Toast.LENGTH_SHORT).show()
            
            // 返回首页
            val intent = Intent(this, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
            finish()
            
        } catch (e: Exception) {
//            Toast.makeText(this, "关闭设备失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
}
